package com.rayboot.footpoint.provider;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Handler;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;

import com.rayboot.footpoint.kml.KMLUtil;
import com.rayboot.footpoint.model.Footprint;
import com.rayboot.footpoint.utils.StorageUtil;
import com.rayboot.footpoint.utils.Util;

public class FootprintsProvider implements ISubProvider {
	private static final Uri BaseURI = Uri
			.parse("content://com.rayboot.footpoint.provider.FootprintContentProvider/footprint");
	public static final String TABLE = "footprint";
	private static final String TAG = "FootprintsProvider";
	Runnable initRunnable = new Runnable() {
		public void run() {
			SharedPreferences localSharedPreferences = FootprintsProvider.this.mContext
					.getSharedPreferences("Footprints", 0);
			boolean bool = localSharedPreferences.getBoolean(keywork, false);
			Util.touchSDFile();
			File localFile = new File(Util.getDBPathOnSD());

			if (!StorageUtil.hasExternalStorage()) {
				return;
			}

			if (!localFile.exists() || localFile.length() == 0L) {
				if (!bool) {
					return;
				}

				SharedPreferences.Editor localEditor = localSharedPreferences
						.edit();
				localEditor.putBoolean(keywork, true);
				localEditor.commit();
				Log.d(TAG, "install preset Footprints");
				InputStream localInputStream = null;
				try {
					localInputStream = FootprintsProvider.this.mContext
							.getAssets().open("preset.kmz");
					Footprint[] arrayOfFootprint = KMLUtil
							.importKMZ(localInputStream);
					FootprintManager.getInstance(
							FootprintsProvider.this.mContext).addFootprint(
							arrayOfFootprint);
					try {
						if (localInputStream != null) {
							localInputStream.close();
						}
					} catch (IOException localIOException4) {
						Log.w(TAG, localIOException4.getMessage(),
								localIOException4);
					}
				} catch (IOException localIOException2) {
					Log.e(TAG, localIOException2.getMessage(),
							localIOException2);
					try {
						if (localInputStream != null) {
							localInputStream.close();
						}
					} catch (IOException localIOException3) {
						Log.w(TAG, localIOException3.getMessage(),
								localIOException3);
					}
				} finally {
				}
				try {
					if (localInputStream != null) {
						localInputStream.close();
					}
				} catch (IOException localIOException1) {
					Log.w(TAG, localIOException1.getMessage(),
							localIOException1);
				}
			}

			if ((FootpointContentProvider.DATABASE_VERSION != Util
					.getExtDBVersion())
					|| (!Util.copyFile(localFile,
							FootprintsProvider.this.mContext
									.getDatabasePath(FootpointContentProvider.DATABASE_NAME)))) {
				FootprintsProvider.this.mContext.getContentResolver()
						.notifyChange(FootprintsProvider.BaseURI, null);
			}

		}
	};
	final String keywork = "PRESET";
	private Context mContext;
	private SQLiteDatabase mDB;

	private boolean isExistData(Footprint paramFootprint) {
		return false;
	}

	private String quoteStr(String paramString) {
		return TextUtils.isEmpty(paramString) ? "" : paramString;
	}

	public int delete(Uri paramUri, String paramString,
			String[] paramArrayOfString) {
		if (FootprintColumns.CONTENT_URI.equals(paramUri))
			return this.mDB.delete(TABLE, paramString, paramArrayOfString);
		throw new IllegalArgumentException("Unknown URI " + paramUri);
	}

	public Uri getBaseURI() {
		return BaseURI;
	}

	public String getType(Uri paramUri) {
		return "";
	}

	public void initPresetData(SQLiteDatabase paramSQLiteDatabase,
			Footprint[] paramArrayOfFootprint) {
		StringBuilder localStringBuilder = new StringBuilder();
		int i = paramArrayOfFootprint.length;
		int j = 0;
		while (true) {
			if (j < i) {
				Footprint localFootprint = paramArrayOfFootprint[j];
				localStringBuilder.setLength(0);
				localStringBuilder.append("insert into footprint(");
				localStringBuilder.append("name").append(",");
				localStringBuilder.append("tel").append(",");
				localStringBuilder.append("addr").append(",");
				localStringBuilder.append("comment").append(",");
				localStringBuilder.append("category").append(",");
				localStringBuilder.append("create_time").append(",");
				localStringBuilder.append("latitude").append(",");
				localStringBuilder.append("longitude").append(",");
				localStringBuilder.append("site").append(",");
				localStringBuilder.append("rate").append(",");
				localStringBuilder.append("version").append(",");
				localStringBuilder.append("audio_path").append(",");
				localStringBuilder.append("pic_path").append(",");
				localStringBuilder.append("accuracy").append(",");
				localStringBuilder.append("pic_name").append(",");
				localStringBuilder.append("audio_name").append(",");
				localStringBuilder.append("audio_length").append(")");
				localStringBuilder.append(" values(");
				localStringBuilder.append(quoteStr(localFootprint.mName))
						.append(",");
				localStringBuilder.append(quoteStr(localFootprint.mTel))
						.append(",");
				localStringBuilder.append(quoteStr(localFootprint.mAddr))
						.append(",");
				localStringBuilder.append(quoteStr(localFootprint.mComment))
						.append(",");
				localStringBuilder.append(quoteStr(localFootprint.mCategory))
						.append(",");
				localStringBuilder.append(localFootprint.mCreateTime).append(
						",");
				localStringBuilder.append(localFootprint.mLatitude).append(",");
				localStringBuilder.append(localFootprint.mLongitude)
						.append(",");
				localStringBuilder.append(quoteStr(localFootprint.mSite))
						.append(",");
				localStringBuilder.append(localFootprint.mRate).append(",");
				localStringBuilder.append(localFootprint.mVersion).append(",");
				localStringBuilder.append(quoteStr(localFootprint.mAudioPath))
						.append(",");
				localStringBuilder.append(quoteStr(localFootprint.mPicPath))
						.append(",");
				localStringBuilder.append(localFootprint.mAccuracy).append(",");
				localStringBuilder
						.append(quoteStr(localFootprint.mPicFileName)).append(
								",");
				localStringBuilder.append(
						quoteStr(localFootprint.mAudioFileName)).append(",");
				localStringBuilder.append("'"
						+ localFootprint.mVoiceSampleLength + "'");
				localStringBuilder.append(")");
			}
			try {
				paramSQLiteDatabase.execSQL(localStringBuilder.toString());
				return;
			} catch (Exception localException) {
			}
		}
	}

	public Uri insert(Uri paramUri, ContentValues paramContentValues) {
		long l = -1L;
		if (paramContentValues == null)
			paramContentValues = new ContentValues();
		if (!FootprintColumns.CONTENT_URI.equals(paramUri))
			throw new IllegalArgumentException("Unknown URI " + paramUri);
		Log.i(TAG, "mDB.replace:" + paramContentValues.getAsString("name"));
		if (FootprintManager.checkContentValues(paramContentValues)) {
			l = this.mDB.replace(TABLE, "name", paramContentValues);
			Log.i(TAG, "rowID = " + String.valueOf(l));
		}
		if (l > 0L)
			;
		for (Uri localUri = ContentUris.withAppendedId(
				FootprintColumns.CONTENT_URI, l);; localUri = null)
			return localUri;
	}

	public void onCreate(SQLiteDatabase paramSQLiteDatabase) {
		paramSQLiteDatabase
				.execSQL("CREATE TABLE footprint (_id integer primary key autoincrement,name TEXT NOT NULL,tel TEXT,addr TEXT,comment TEXT,category TEXT,create_time LONG NOT NULL,latitude INTEGER NOT NULL,longitude INTEGER NOT NULL,site TEXT,rate INTEGER,drawable_id LONG,version INTEGER,audio_path TEXT,pic_path TEXT,accuracy INTEGER NOT NULL,pic_name TEXT,audio_name TEXT,audio_length float,short_date TEXT);");
		new Handler().postDelayed(this.initRunnable, 10L);
	}

	public void onDrop(SQLiteDatabase paramSQLiteDatabase) {
		paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS footprint");
	}

	public Cursor query(Uri paramUri, String[] paramArrayOfString1,
			String paramString1, String[] paramArrayOfString2,
			String paramString2) {
		SQLiteQueryBuilder localSQLiteQueryBuilder = new SQLiteQueryBuilder();
		if (FootprintColumns.CONTENT_URI.equals(paramUri)) {
			localSQLiteQueryBuilder.setTables(TABLE);
			return localSQLiteQueryBuilder
					.query(this.mDB, paramArrayOfString1, paramString1,
							paramArrayOfString2, null, null, paramString2);
		}
		throw new IllegalArgumentException("Unknown URL " + paramUri);
	}

	public void setContext(Context paramContext) {
		this.mContext = paramContext;
	}

	public void setDB(SQLiteDatabase paramSQLiteDatabase) {
		this.mDB = paramSQLiteDatabase;
	}

	public int update(Uri paramUri, ContentValues paramContentValues,
			String paramString, String[] paramArrayOfString) {
		if (FootprintColumns.CONTENT_URI.equals(paramUri))
			return this.mDB.update(TABLE, paramContentValues, paramString,
					paramArrayOfString);
		throw new IllegalArgumentException("Unknown URL " + paramUri);
	}

	public static final class FootprintColumns implements BaseColumns {
		public static final String ACCURACY = "accuracy";
		public static final String ADDR = "addr";
		public static final String AUDIO_LENGTH = "audio_length";
		public static final String AUDIO_NAME = "audio_name";
		public static final String AUDIO_PATH = "audio_path";
		public static final String CATEGORY = "category";
		public static final String COMMENT = "comment";
		public static final Uri CONTENT_URI = FootprintsProvider.BaseURI;
		public static final String CREATE_TIME = "create_time";
		public static final String DRAWABLE_ID = "drawable_id";
		public static final String ID = "_id";
		public static final String LATITUDE = "latitude";
		public static final String LONGITUDE = "longitude";
		public static final String NAME = "name";
		public static final String PIC_NAME = "pic_name";
		public static final String PIC_PATH = "pic_path";
		public static final String RATE = "rate";
		public static final String SHORT_DATE = "short_date";
		public static final String SITE = "site";
		public static final String TEL = "tel";
		public static final String VERSION = "version";
	}
}
